package org.example.cloudgetway.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;

import java.util.Date;

public class JwtUtils {
    // 密钥
    public static final String KEY = "asdasdfas-12344566";
    // token过期时间
    public static final long TOKEN_EXPIRE_TIME = 5 * 60 * 1000;
    // 签发人
    public static final String ISSUER = "tang";

    public static final String USER_NAME = "username";

    public static String getToken(String username){
        Algorithm algorithm = Algorithm.HMAC256(KEY);
        String sign = JWT.create()
                .withIssuer(ISSUER)
                .withIssuedAt(new Date())
                .withExpiresAt(new Date(new Date().getTime() + TOKEN_EXPIRE_TIME))
                .withClaim(USER_NAME, username)
                .sign(algorithm);
        return sign;
    }
    public static boolean verify(String token){
        try {
            Algorithm algorithm = Algorithm.HMAC256(KEY);
            JWTVerifier verifier = JWT.require(algorithm).withIssuer(ISSUER).build();
            verifier.verify(token);
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }


    public static void main(String[] args) {
        String token = JwtUtils.getToken("tang");
        boolean verify = JwtUtils.verify(token);
        System.out.println(verify);
    }

}
